package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();//获取response
        ServerHttpRequest request = exchange.getRequest();//获取request
        //判断是否为登录
        if (request.getURI().getPath().contains("/login_auth")) {//判断路径中是否包含登录地址
            //有,就直接放行
            return chain.filter(exchange);
        }
        //从请求头获取用户的token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {//判断是否token是否为空
            //为空返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//结束请求
        }
        //判断token的状态
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i == 1 || i == 2) {//如果为1或2就是过期状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//结束请求
        }
        //到这一步就通过放行
        return chain.filter(exchange);
    }


    //返回排序数字,越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
